<?php
namespace app\common\service;

use app\common\model\GoodsSpecItemModel;
use app\common\model\GoodsSpecModel;
use common\util\ArrayUtil;
use app\common\model\GoodsSpecGoodsPriceModel;

class GoodsSpecService {

    public static function getGoodsSpecList($goods_type_id,$needAll=true) {
        $goodsSpecs = GoodsSpecModel::instance()->where('goods_type_id', $goods_type_id)
            ->order('order', 'desc')
            ->select();
        $goodsSpecs = collection($goodsSpecs)->toArray();
        $goodsSpecIds = ArrayUtil::getKeyValuesFromArray($goodsSpecs, 'id');
        $goodsSpecIdMap = []; // 规格项目map 一个规格对应几个规格项
        if ($goodsSpecIds) {
            $goodsSpecItems = GoodsSpecItemModel::instance()->whereIn('goods_spec_id', $goodsSpecIds)->select();
            $goodsSpecItems = collection($goodsSpecItems)->toArray();
            $goodsSpecIdMap = ArrayUtil::group($goodsSpecItems, 'goods_spec_id');
        }

        $result= [];
        
        foreach ($goodsSpecs as &$goodsSpec) {
            $goodsSpecId = $goodsSpec['id'];
            $goodsSpec['values'] = [];
            if (array_key_exists($goodsSpecId, $goodsSpecIdMap)) {
                $goodsSpec['values'] = $goodsSpecIdMap[$goodsSpecId];
                $result [] = $goodsSpec;
            }
        }
        return $needAll ? $goodsSpecs : $result;
    }

    /**
     * 获取产品规格对应的库存和价格
     *
     * @param array $goods
     * @return array
     */
    public static function getGoodsPriceMap($goods) {
        $goodsId = $goods['id'];
        return GoodsSpecGoodsPriceModel::instance()->where('goods_id', $goodsId)->column('key,key_name,price,store_count', 'key');
    }
}